<template>
  <view class="container">
   
    <button @click="downloadImage" :disabled="isDownloading">
      {{ isDownloading ? '下载中...' : '下载图片' }}
    </button>
    
    
    <view v-if="progress > 0 && progress < 100" class="progress">
      下载进度：{{ progress }}%
    </view>
    
    
    <view v-if="downloadResult" class="result">
      {{ downloadResult }}
    </view>
    
   
    <view v-if="localImagePath" class="image-container">
      <image :src="localImagePath" mode="widthFix" class="downloaded-img"></image>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: "https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg",
      localImagePath: "", 
      progress: 0, 
      isDownloading: false, 
      downloadResult: "" 
    };
  },
  methods: {
    downloadImage() {
   
      this.progress = 0;
      this.downloadResult = "";
      this.isDownloading = true;
      
     
      const downloadTask = uni.downloadFile({
        url: this.imageUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            
            this.localImagePath = res.tempFilePath;
            this.downloadResult = "下载成功！";
            console.log("LOGO: 图片下载完成，路径：", res.tempFilePath);
          } else {
            this.downloadResult = "下载失败，状态码：" + res.statusCode;
            console.log("LOGO: 下载失败，状态码：", res.statusCode);
          }
        },
        fail: (err) => {
          this.downloadResult = "下载失败：" + err.errMsg;
          console.log("LOGO: 下载出错：", err.errMsg);
        },
        complete: () => {
          this.isDownloading = false;
          this.progress = 0;
        }
      });
      
      
      downloadTask.onProgressUpdate((res) => {
        this.progress = res.progress;
       
        console.log(`LOGO: 下载进度：${res.progress}%，已下载${(res.totalBytesWritten/1024).toFixed(1)}KB`);
      });
    }
  }
};
</script>

<style>
.container {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.progress {
  color: #007aff;
  font-size: 28rpx;
}

.result {
  font-size: 28rpx;
  color: #ff3b30;
}

.image-container {
  margin-top: 30rpx;
}

.downloaded-img {
  width: 100%;
  border-radius: 8rpx;
}

button {
  background-color: #007aff;
  color: white;
}
</style>